# 架构说明：
# 1. 日志生产者 -> 2. 原始日志Topic -> 3. 处理程序 -> 4. 统计结果Topic
import json
import pika
from datetime import datetime

logs = [
    '127.0.0.1 - "GET /index.html HTTP/1.1" 200 432',
    '192.168.1.1 - "POST /login HTTP/1.1" 401 128',
    '10.0.0.5 - "GET /product/123 HTTP/1.1" 200 892'
]

# Connection parameters
credentials = pika.PlainCredentials('XuYixuan', 'Xyx20040422')
connection = pika.BlockingConnection(pika.ConnectionParameters('82.156.163.134', 5672, '/', credentials))
channel = connection.channel()

channel.queue_declare(queue='logs')

for log in logs:
    message = json.dumps({'log': log})
    channel.basic_publish(exchange='',
                          routing_key='logs',
                          body=message.encode('utf-8'))

def callback(ch, method, properties, body):
    log = json.loads(body)['log']
    # 解析日志条目
    parts = log.split()
    ip = parts[0]
    method = parts[3].strip('"')
    status = parts[5]

    # 生成统计信息
    stats = {
        'ip': ip,
        'status': status,
        'method': method,
        'timestamp': datetime.now().isoformat()
    }
    print(stats)

channel.basic_consume(queue='logs', on_message_callback=callback, auto_ack=True)

print('Waiting for messages. To exit press CTRL+C')
channel.start_consuming()